package com.lms.common.pure.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PinyinUtil {

    public static String getFullSpellSmallLetter(String text) {
        if (text == null) return null;
        String s = getFullSpell(text);
        return s.toLowerCase();
    }

    public static String getFullSpell(String text) {
        if (text == null) return null;
        // 用StringBuffer（字符串缓冲）来接收处理的数据
        StringBuilder sb = new StringBuilder();
        //字符串转换字节数组
        char[] arr = text.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        //转换类型（大写or小写）
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //定义中文声调的输出格式
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //定义字符的输出格式
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_U_AND_COLON);
        for (char c : arr) {
            //判断是否是汉子字符
            if (c > 128) {
                try {
                    sb.append(capitalize(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]));
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                // 如果不是汉字字符，直接拼接
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static boolean isChineseText(Serializable character) {
        if (character == null) return false;
        Pattern pattern = Pattern.compile("^[\\u4e00-\\u9fa5]");
        Matcher matcher = pattern.matcher(character.toString());
        return matcher.find();
    }

    public static String capitalize(String str) {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }
        return new String(ch);
    }
}
